package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysFileInfo;
import com.ruoyi.system.em.SourceTableEnum;
import com.ruoyi.system.mapper.SysFileInfoMapper;
import com.ruoyi.system.service.ISysFileInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件信息Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-30
 */
@Service
public class SysFileInfoServiceImpl extends ServiceImpl<SysFileInfoMapper, SysFileInfo> implements ISysFileInfoService {

    @Override
    public List<SysFileInfo> selectFileInfoBySource(SourceTableEnum sourceTableEnum, String sourceId) {
        if (sourceId.isEmpty()) {
            return new ArrayList<>();
        }
        SysFileInfo query = new SysFileInfo();
        query.setSourceId(sourceId);
        query.setSourceTable(sourceTableEnum.value());
        return getBaseMapper().selectList(buildQueryWrapper(query));
    }

    @Override
    public SysFileInfo selectFileInfoBySourceOne(SourceTableEnum sourceTableEnum, String sourceId) {
        List<SysFileInfo> sysFileInfos = selectFileInfoBySource(sourceTableEnum, sourceId);
        if (sysFileInfos.size() > 1){
            throw new RuntimeException("使用selectOne接口查到了多个文件");
        }
        if (sysFileInfos.size() == 1){
            return sysFileInfos.get(0);
        }
        return null;
    }

    @Override
    public List<SysFileInfo> selectByUrls(List<String> urls) {
        urls = urls.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
        if (urls.isEmpty()) return new ArrayList<>();
        return getBaseMapper().selectList(Wrappers.lambdaQuery(SysFileInfo.class).in(SysFileInfo::getUrl, urls));
    }

    @Override
    @Transactional
    public void relationCreateFileInfo(SourceTableEnum sourceTableEnum, String sourceId, List<String> fileUrls) {
        if (fileUrls.isEmpty()) {
            return;
        }
        List<SysFileInfo> sysFileInfos = selectByUrls(fileUrls);

        sysFileInfos.forEach(res -> {
            res.setSourceId(sourceId);
            res.setSourceTable(sourceTableEnum.value());
            res.setCreateTime(new Date());
        });

        updateBatchById(sysFileInfos);
    }

    @Override
    @Transactional
    public void relationUpdateFileInfo(SourceTableEnum sourceTableEnum, String sourceId, List<String> fileUrls) {
        // 取现有的
        SysFileInfo query = new SysFileInfo();
        query.setSourceId(sourceId);
        query.setSourceTable(sourceTableEnum.value());
        List<SysFileInfo> oldDbs = getBaseMapper().selectList(buildQueryWrapper(query));
        List<String> oldUrls = oldDbs.stream().map(SysFileInfo::getUrl).collect(Collectors.toList());
        // 要新增的
        List<String> addUrls = new ArrayList<>(fileUrls);
        addUrls.removeAll(oldUrls);
        if (!addUrls.isEmpty()) {
            relationCreateFileInfo(sourceTableEnum, sourceId, addUrls);
        }
        // 要删除的
        List<String> delUrls = new ArrayList<>(oldUrls);
        delUrls.removeAll(fileUrls);
        if (!delUrls.isEmpty()) {
            getBaseMapper().delete(Wrappers.lambdaQuery(SysFileInfo.class).in(SysFileInfo::getUrl, delUrls));
            for (String delUrl : delUrls) {
                fileRealDelete(delUrl);
            }
        }
    }

    @Override
    @Transactional
    public void relationDeleteFileInfo(SourceTableEnum sourceTableEnum, List<String> sourceIds) {
        LambdaQueryWrapper<SysFileInfo> query = Wrappers.lambdaQuery();
        query.in(!sourceIds.isEmpty(), SysFileInfo::getSourceId, sourceIds);
        query.eq(SysFileInfo::getSourceTable, sourceTableEnum.value());
        List<SysFileInfo> sysFileInfoList = getBaseMapper().selectList(query);
        if (!sysFileInfoList.isEmpty()) {
            getBaseMapper().deleteBatchIds(sysFileInfoList.stream().map(SysFileInfo::getId).collect(Collectors.toList()));
            for (SysFileInfo sysFileInfo : sysFileInfoList) {
                fileRealDelete(sysFileInfo.getUrl());
            }
        }
    }

    /**
     * 删除磁盘文件
     */
    private void fileRealDelete(String url) {
        int indexOf = url.indexOf("/profile/upload");
        if (indexOf != -1) {
            url = RuoYiConfig.getUploadPath() + url.substring(15);
            new File(url).delete();
        }
    }

    private LambdaQueryWrapper<SysFileInfo> buildQueryWrapper(SysFileInfo query) {
        Map<String, Object> params = query.getParams();
        LambdaQueryWrapper<SysFileInfo> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(query.getOriginalName()), SysFileInfo::getOriginalName, query.getOriginalName());
        lqw.eq(StringUtils.isNotBlank(query.getUrl()), SysFileInfo::getUrl, query.getUrl());
        lqw.like(StringUtils.isNotBlank(query.getExtName()), SysFileInfo::getExtName, query.getExtName());
        lqw.eq(StringUtils.isNotBlank(query.getSourceId()), SysFileInfo::getSourceId, query.getSourceId());
        lqw.eq(query.getSourceTable() != null, SysFileInfo::getSourceTable, query.getSourceTable());
        return lqw;
    }

}
